package com.psa.element;

import android.content.ContentValues;
import android.database.Cursor;
import com.google.gson.Gson;
import com.psa.tool.DBTool;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author david
 * @date 2014/4/22
 */
public class District implements IJson,ISqlObject {
    public String ID = "";
    public String ChineseName = "";
    public String EnglishName = "";
    public String Routine = "0";

    @Override
    public String toJson() {
        return new Gson().toJson(this);
    }

    @Override
    public int insert(DBTool dbTool) {
        ContentValues values = new ContentValues();
        values.put("ID", ID.trim());
        values.put("ChineseName", ChineseName.trim());
        values.put("EnglishName", EnglishName.trim());
        values.put("Routine", Routine.trim());
        return (int)dbTool.insert("District", values);
    }

    @Override
    public int update(DBTool dbTool) {
        ContentValues values = new ContentValues();
        values.put("ChineseName", ChineseName.trim());
        values.put("EnglishName", EnglishName.trim());
        values.put("Routine", Routine.trim());
        String where = "ID = ?";
        String[] whereval = { ID.trim() };
        return dbTool.update("District", values, where, whereval);
    }

    @Override
    public int delete(DBTool dbTool) {
        String where = "ID = ?";
        String[] wherevalue = { ID.trim() };
        return dbTool.delete("District", where, wherevalue);
    }

    @Override
    public String toString() {
        return (ID==null?"":ID.trim()) + " " + (ChineseName==null?"":ChineseName.trim());
    }

    @Override
    public ISqlObject full(Cursor cursor) {
        if (cursor!=null && cursor.moveToNext()) {
            District district = new District();
            district.ID = cursor.getString(0);
            district.ChineseName = cursor.getString(1);
            district.EnglishName = cursor.getString(2);
            district.Routine = cursor.getString(3);
            return district;
        }
        return null;
    }

    @Override
    public void clear(DBTool dbTool) {
        dbTool.execSQL("Delete From District Where 1=1");
//        dbTool.delete("District", "ID Like ?", new String[]{"%"});
    }

    @Override
    public String getDataSql() {
        return "Route";
    }

    @Override
    public String getSyncMethod() {
        return "getdataobjects";
    }

    public static List<District> getDistrictList() {
        List<District> districts = new ArrayList<>();
        String sql = "Select * From District";
        District district = new District();
        Cursor cursor = DBTool.getInstance().query(sql);
        while ((district = (District)district.full(cursor)) != null) {
            districts.add(district);
        }
        cursor.close();
        return districts;
    }
}
